<template>
  <div class="register-container">
    <div class="register-form-wrapper">
      <h2>用户注册</h2>
      <n-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-placement="top"
      >
        <n-form-item label="用户名" path="username">
          <n-input
            v-model:value="formData.username"
            placeholder="请输入用户名"
            :prefix-icon="Person"
          />
        </n-form-item>
        
        <n-form-item label="密码" path="password">
          <n-input
            v-model:value="formData.password"
            type="password"
            placeholder="请输入密码（至少6位）"
            :prefix-icon="LockClosed"
          />
        </n-form-item>
        
        <n-form-item label="确认密码" path="confirmPassword">
          <n-input
            v-model:value="formData.confirmPassword"
            type="password"
            placeholder="请再次输入密码"
            :prefix-icon="LockClosed"
          />
        </n-form-item>
        
        <n-form-item label="邮箱（可选）" path="email">
          <n-input
            v-model:value="formData.email"
            placeholder="请输入邮箱"
            :prefix-icon="Mail"
          />
        </n-form-item>
        
        <n-form-item>
          <n-button
            type="primary"
            block
            @click="handleRegister"
            :loading="loading"
          >
            {{ loading ? '注册中...' : '注册' }}
          </n-button>
        </n-form-item>
        
        <div class="login-link">
          <span>已有账号？</span>
          <n-button
            type="link" as any
            @click="goToLogin"
          >
            立即登录
          </n-button>
        </div>
      </n-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { Person, LockClosed, Mail } from '@vicons/ionicons5'
import { authService } from '../services/auth-service'
import { useMessage } from 'naive-ui'
import { useAuthModalStore } from '../stores/authModal'
const message = useMessage()
const authModalStore = useAuthModalStore()

const router = useRouter()
const formRef = ref()
const loading = ref(false)

const formData = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  email: ''
})

const rules = {
  username: [
    {
      required: true,
      message: '请输入用户名',
      trigger: 'blur'
    }
  ],
  password: [
    {
      required: true,
      message: '请输入密码',
      trigger: 'blur'
    },
    {
      min: 6,
      message: '密码长度至少为6位',
      trigger: 'blur'
    }
  ],
  confirmPassword: [
    {
      required: true,
      message: '请确认密码',
      trigger: 'blur'
    },
    {
      validator: (_rule: any, value: string) => {
        if (!value || formData.password === value) {
          return new Promise((resolve) => resolve(true))
        }
        return new Promise((_resolve, reject) => {
          reject(new Error('两次输入的密码不一致'))
        })
      },
      trigger: 'blur'
    }
  ],
  email: [
    {
      pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
      message: '请输入有效的邮箱地址',
      trigger: 'blur',
      required: false
    }
  ]
}

const handleRegister = async () => {
  if (!formRef.value) return
  
  try {
    const valid = await formRef.value.validate()
    if (valid) {
      loading.value = true
      
      const result = await authService.register({
        username: formData.username,
        password: formData.password,
        email: formData.email
      })
      
      // 注册成功后
      if (result && result.code === 0) {
        // 显示成功提示
        message.success(result.data || '注册成功，请登录')
        
        // 延迟一小段时间再显示登录弹窗，让用户看到成功提示
        setTimeout(() => {
          console.log('注册成功，显示登录弹窗')
          // 显示登录弹窗而不是跳转到登录页面
          authModalStore.showAuthModal()
          // 跳转到首页
          router.push('/')
        }, 1000)
      } else {
        throw new Error(result?.msg || '注册失败，请稍后重试')
      }
    }
  } catch (error) {
    console.error('注册失败: ', error);
    // 显示错误提示
    if (error instanceof Error) {
      message.error(error.message || '注册失败，请稍后重试')
    } else {
      message.error('注册失败，请稍后重试')
    }
  } finally {
    loading.value = false
  }
}

const goToLogin = () => {
  // 显示登录弹窗而不是跳转到登录页面
  authModalStore.showAuthModal()
  // 跳转到首页
  router.push('/')
}
</script>

<style scoped>
.register-container {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
  width: 100vw;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.register-form-wrapper {
  width: 400px;
  padding: 30px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.register-form-wrapper h2 {
  text-align: center;
  margin-bottom: 24px;
  color: #333;
}

.login-link {
  text-align: center;
  margin-top: 16px;
}

.login-link span {
  color: #666;
}
</style>